package com.open.party.cloud.view.home.jiCengDangJian.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.android.x.model.data.ResultInfo
import cn.sinothk.hussars.views.BaseFragment
import cn.sinothk.map.amap.base.MapCallback
import cn.sinothk.map.amap.location.AMapLocate
import cn.sinothk.map.amap.location.AMapLocationEntity
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.MyLocationStyle
import com.open.party.cloud.R
import com.open.party.cloud.model.TimeBean
import com.open.party.cloud.model.ZyzKaoQingBean
import com.open.party.cloud.view.home.jiCengDangJian.TimePlanListActivity
import com.open.party.cloud.view.home.jiCengDangJian.partyService.ZyzKaoQingMainActivity
import com.open.party.cloud.viewModel.ZiYuanZheViewModel
import com.sinothk.android.utils.XUtils
import kotlinx.android.synthetic.main.zyz_fragment_singin_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

open class ZyzSignInMainFragment : BaseFragment() {
    var ziYuanZheVM: ZiYuanZheViewModel? = null
    private var currView: View? = null
    private var aMap: AMap? = null

    private var configId = ""

    private var parentActivity: ZyzKaoQingMainActivity? = null

    override fun onAttach(context: Context) {
        super.onAttach(context)
        parentActivity = context as ZyzKaoQingMainActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        if (currView == null) {
            currView = inflater.inflate(R.layout.zyz_fragment_singin_main, container, false)
        }
        EventBus.getDefault().register(this)
        return currView
    }

    private fun initMapView(savedInstanceState: Bundle?) {
        mMapView.onCreate(savedInstanceState)
        if (aMap == null) {
            aMap = mMapView.map
            initLocMap()
        }
    }

    private fun initLocMap() {
        val myLocationStyle =
            MyLocationStyle() //初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        //        myLocationStyle.interval(24 * 60 * 60 * 1000); //10 * 1000 设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
        //        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.push_pin_72)));
        myLocationStyle.strokeColor(Color.TRANSPARENT)
        myLocationStyle.radiusFillColor(Color.TRANSPARENT)
        //        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE);
        aMap!!.myLocationStyle = myLocationStyle //设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        setMapSetting()
        //设置缩放比例
        aMap!!.moveCamera(CameraUpdateFactory.zoomTo(15f));
        aMap!!.isMyLocationEnabled = true // 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }

    private fun setMapSetting() {
        val mUiSettings = aMap!!.uiSettings //实例化UiSettings类对象
        //        aMap.setLocationSource(this);//通过aMap对象设置定位数据源的监听
//        mUiSettings.setCompassEnabled(true); // 指南针用于向 App 端用户展示地图方向，默认不显示。通过如下接口控制其显示：
        mUiSettings.isZoomControlsEnabled = false
        //        mUiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
        mUiSettings.isMyLocationButtonEnabled = true //显示默认的定位按钮
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)

        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mMapView != null) {
            mMapView.onDestroy()
            return
        }
    }

    override fun onResume() {
        super.onResume()
        if (mMapView != null) {
            //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
            mMapView.onResume()
            return
        }
    }

    override fun onPause() {
        super.onPause()
        if (mMapView != null) {
            //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
            mMapView.onPause()
            return
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        if (mMapView != null) {
            //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
            mMapView.onSaveInstanceState(outState)
            return
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        initMapView(savedInstanceState)
//        timeTv.text = XUtils.date().getDateStrByDate(Date(), "HH:mm:ss")
        ziYuanZheVM = ZiYuanZheViewModel()

        signInBtn.setOnClickListener {

            if (XUtils.string().isEmpty(configId)) {
                XUtils.toast().show("请选择签到时间段")
                return@setOnClickListener
            }

            showLoadingDialog("正在提交")

            AMapLocate().locationOnce(activity, object: MapCallback<AMapLocationEntity> {
                override fun onSuccess(locInfo: AMapLocationEntity) {
                    when (locInfo.code) {
                        0 -> {
                            val vo = ZyzKaoQingBean()
                            vo.activityId = parentActivity!!.activityId
                            vo.lon = locInfo.longitude.toString()
                            vo.lat = locInfo.latitude.toString()
                            vo.addr = locInfo.address
                            vo.configId = configId
                            ziYuanZheVM!!.doActivitySignIn(vo)
                        }
                        else -> {
                            hideLoadingDialog()
                            XUtils.toast().show("定位失败，请检查后重试")
                        }
                    }
                }

                override fun onFail(msg: String?) {
                }
            })
        }

        timeListView.setOnClickListener {
            XUtils.intent().openActivity(parentActivity, TimePlanListActivity::class.java)
                .putStringExtra("activityId", parentActivity!!.activityId)
                .requestCode(500).startInFragment(this)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun eventBusCallback(result: ResultInfo<Boolean>) {
        if (result.eventType != "doActivitySignIn") {
            return
        }
        hideLoadingDialog()
        when (result.code) {
            ResultInfo.SUCCESS -> {
                if (result.data) {
                    XUtils.toast().show("签到成功")
                } else {
                    XUtils.toast().show(result.msg)
                }
            }
            ResultInfo.TOKEN_OVERDUE -> {
            }
            else -> {
                XUtils.toast().show(result.msg)
            }
        }
    }


    @SuppressLint("SetTextI18n")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        when {
            requestCode == 500 && resultCode == 200 && data != null -> {
                val timeBean: TimeBean = data.getSerializableExtra("value") as TimeBean

                configId = timeBean.id

                val startTime = timeBean.serviceStartTime
                val endTime = timeBean.serviceEndTime

                if (startTime != null && endTime != null) {
                    val sTimeStr = XUtils.date().getDateStrByDate(startTime, "yyyy-MM-dd HH:mm")
                    val eTimeStr = XUtils.date().getDateStrByDate(endTime, "HH:mm")
                    timeListTv.text = "签到时间段：$sTimeStr - $eTimeStr"
                }
            }
        }
    }
}